# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations

def files():
    response.headers['Content-Type']='application/json'
    response.headers['Content-Disposition']='attachment;filename=catalog.json'
    args=request.args
    if args and args[0]=='demo':
        import datetime
        host = request.env.http_host.split('://')[-1]
        filename = URL('static','data/demo.nersc')
        files=[dict(filename='demo.nersc',size=393674,
                    mtime=datetime.datetime.now().isoformat(),
                    link='http://%s%s' % (host,filename))]
        return response.json(dict(files=files,token='None'))
    if len(args)<3 or db(db.token.uuid==args[0]).isempty():
        return response.json(dict(error='not authorized'))
    token,path,pattern = args[0],'/'.join(args[1:-1]),args[-1]    
    c = db.catalog_file
    root_id = db.catalog_folder(path=path).id
    files = db(c.root_id==root_id)(c.pattern==pattern).select(
        c.filename,c.size,c.mtime)
    for file in files:
        file.link = getfile(file.filename)
    return response.json(dict(files=files,token=token))
